package com.jgp.component;

import com.jgp.common.utils.ReflectUtil;
import com.jgp.sys.ui.Result;
import com.jgp.sys.utils.ResultUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;
import java.util.Objects;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2019-11-06
 */
@RestControllerAdvice
public class ResultAdvice implements ResponseBodyAdvice {
    
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return !String.class.isAssignableFrom(returnType.getParameterType()) && !ReflectUtil.isBaseClass(returnType.getParameterType()) &&(!returnType.getParameterType().isArray())  && MappingJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
    }
    
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        
        HttpHeaders headers = request.getHeaders();
        List<String> client = headers.get("__JGP_MICRO_CLIENT__");
        
        if (Objects.nonNull(client) && "yes".equals(client.get(0))) {
            Class clazz = returnType.getParameterType();
            if (Result.class.isAssignableFrom(clazz)) {
                Result result = (Result)body;
                return result.operatorModelExtData();
            }else return body;
        } else {
            Class clazz = returnType.getParameterType();
            if (Result.class.isAssignableFrom(clazz)) {
                Result result = (Result) body;
                return result.operatorModelExtData();
            } else {
                return ResultUtil.operatorModelExtData(body);
            }
        }
    }
    
}
